package controller

import (
	"admin/app/http/response"
	"admin/app/model"
	"admin/app/service"
	"admin/constant"
	"github.com/google/uuid"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

type NoteController struct {
}

func NoteRegister(noteGrp *gin.RouterGroup) {
	noteController := &NoteController{}
	noteGrp.Use().POST("/save", noteController.noteSave)
	noteGrp.Use().GET("/read", noteController.noteRead)
	noteGrp.Use().POST("/migrate", noteController.migrate)
	noteGrp.Use().GET("/list", noteController.noteList)
}

// 保存笔记
func (n NoteController) noteSave(ctx *gin.Context) {
	var body struct {
		ID      string `json:"id"`
		Title   string `json:"title"`
		Content string `json:"content"`
	}

	//绑定json和结构体
	if err := ctx.BindJSON(&body); err != nil {
		return
	}
	var note model.Note
	currentTime := time.Now()
	timeString := currentTime.Format("2006-01-02 15:04:05")
	if body.ID != "" {
		var err error
		note, err = service.ReadNote(body.ID)
		note.UpdatedAt = timeString
		if err != nil {
			response.Success(ctx, 10001, "笔记不存在", gin.H{})
			return
		}
	} else {
		note.ID = uuid.New().String()
	}
	note.Title = body.Title
	note.Content = body.Content
	note.CreatedAt = timeString

	_, err := service.SaveNote(note)
	if err != nil {
		response.Success(ctx, 20001, "保存失败", gin.H{})
		return
	} else {
		response.Success(ctx, constant.SelectSuccessCode, "保存成功", gin.H{})
		return
	}

}

func (n NoteController) noteRead(ctx *gin.Context) {

	id := ctx.Query("id")
	var note model.Note

	var err2 error
	note, err2 = service.ReadNote(id)
	if err2 != nil {
		response.Success(ctx, 20001, "笔记不存在", gin.H{})
		return
	} else {
		response.Success(ctx, constant.SelectSuccessCode, "保存成功", note)
		return
	}

}

func (n NoteController) noteList(ctx *gin.Context) {
	page, err := strconv.Atoi(ctx.Query("page"))
	if err != nil {
		page = 1
	}

	pageSize, err := strconv.Atoi(ctx.Query("pageSize"))
	if err != nil {
		pageSize = 10
	}
	list, total := service.ListNote(page, pageSize)
	response.SuccessPage(ctx, list, total)
}

func (n NoteController) migrate(ctx *gin.Context) {
	response.Success(ctx, constant.SelectSuccessCode, constant.SelectSuccessMsg, gin.H{"note": "aa"})
}
